export type ListInfo = {
  idField: string
  pidField: string
  nameField: string
  status?: number
}
export type TreeType = {
  children: Array<TreeType>
  title: string
  key: string
}

export type ListTreeType = Array<TreeType & Partial<ListInfo>>
/**
 *
 * @param nodeList 菜单树形编辑节点
 * @param pid 父id
 * @param disabledTag 是否依照参数设置disable属性
 * @returns
 */
export function listToTree<T>(
  nodeList: T extends ListInfo[] ? T : never,
  pid: number | string,
  disabledTag = false,
): ListTreeType {
  const rootNode = nodeList.filter((node) => node[node.idField as keyof ListInfo] === pid)

  if (rootNode.length === 0) {
    return []
  }

  const node: ListTreeType = rootNode.map((nodeInfo) => {
    const dtag = disabledTag ? (nodeInfo.status === 1 ? false : true) : disabledTag
    return {
      ...nodeInfo,
      key: nodeInfo[nodeInfo.idField as keyof ListInfo]!.toString(),
      disabled: dtag,
      title: nodeInfo[nodeInfo.nameField as keyof ListInfo]!.toString(),
      children: listToTree(nodeList, nodeInfo[nodeInfo.idField as keyof ListInfo]!),
    }
  })

  return node
}
